#!/bin/bash

if [[ $(whoami) != "root" ]]; then
	echo "Please login as user root";
	exit 3;
fi

if [[ $LFS == "" ]]; then
	echo "LFS environment not valid...";
	exit 1;
fi

if [ ! -d $LFS ]; then
	echo "LFS directory $LFS dosn'r exists";
	exit 2;
fi

# get target name
LFS_TGT="$(uname -m)-$(cat $LFS/sources/distname | tr -d '[:space:]')" || exit 3;

mkdir -pv $LFS/sources && \
mkdir -pv $LFS/etc && \
chmod -v a+wt $LFS/sources && \
wget -nc -i wget-list -P $LFS/sources && \
rm -fv /tools && \
mkdir -pv $LFS/tools && \
ln -sfv $LFS/tools /

if (( $? != 0 )); then
	echo "Preparing of tools folder failed";
	exit 3;
fi

echo "Check if user lfs exists"
if [[ $(cat /etc/passwd | grep '^lfs:') != "" ]]; then
	echo "user lfs already created, nothing to do...";
else
	echo "create user lfs";
	groupadd -f lfs && \ 
	useradd -s /bin/bash -g lfs -m -k /dev/null lfs || (echo "Aborted" && exit 4);
fi

# set user environment
LFS_HOME=$(cat /etc/passwd | grep '^lfs:' | cut -d: -f6) && \
chown -vR lfs $LFS/tools && \
chown -vR lfs $LFS/sources && \
chown -vR lfs $LFS/etc && \
LINKER_PLATFORM=$(readelf -l /bin/bash | grep interpreter | sed 's/^.*:\(.*\)]/\1/g' | tr -d ' ') && \
echo "host platform linker: $LINKER_PLATFORM found" && \
if [[ $LFS_HOME == "" ]]; then echo "Abort, because wrong home environment value $LFS_HOME"; exit 5; fi && \
echo "exec env -i HOME=$LFS_HOME TERM=$TERM PS1='\u:\w\$ ' /bin/bash" > $LFS_HOME/.bash_profile && \
MAKEFLAGS="-j"$(cat /proc/cpuinfo | grep '^processor.*:.*$' | wc -l) && \
if (( $? != 0 )); then MAKEFLAGS="-j1"; fi && \
echo "set +h
umask 022
LFS=/mnt/lfs
LC_ALL=POSIX
LINKER_PLATFORM=$LINKER_PLATFORM
MAKEFLAGS=$MAKEFLAGS
LFS_TGT=$LFS_TGT
PATH=/tools/bin:/bin:/usr/bin
export LFS LC_ALL LFS_TGT PATH MAKEFLAGS LINKER_PLATFORM
echo \"
Welcome to the LFS tool environment!
See $LFS/sources for package archives... Your are now able to build tools from chapter 5 of the LFS book.

Environment info:
	LFS=\$LFS
	HOME=\$HOME
	MAKEFLAGS=\$MAKEFLAGS
	LFS_TGT=\$LFS_TGT
	PATH=\$PATH
	LC_ALL=\$LC_ALL
	LINKER_PLATFORM=\$LINKER_PLATFORM
	
cd \$LFS/sources
\"" > $LFS_HOME/bashrc_lfs && \
chmod +x $LFS_HOME/bashrc_lfs && \
BASHRC_LFS="[ ! -x $LFS_HOME/bashrc_lfs ] || source $LFS_HOME/bashrc_lfs;" && \
[ ! -z $(cat $LFS_HOME/.bashrc | grep "^$BASHRC_LFS$") ] || echo $BASHRC_LFS >> $LFS_HOME/.bashrc && \
chown -vR lfs:lfs $LFS_HOME && \
su - lfs || echo "Failed 'su - lfs'" && \
rm -f $LFS_HOME/.bash_profile && \
rm -f $LFS_HOME/bashrc_lfs;
